<template>
    <el-form :model="form" ref="ruleFormRef" :rules="rules" label-width="100">
        <el-form-item label="旧密码" prop="old">
            <el-input v-model="form.old" />
        </el-form-item>
        <el-form-item label="新密码" prop="new">
            <el-input v-model="form.new" type="password" show-password />
        </el-form-item>
        <el-form-item label="重复密码" prop="new2">
            <el-input v-model="form.new2" type="password" show-password />
        </el-form-item>
        <el-form-item>
            <el-button
                :loading="submitLoading"
                type="primary"
                @click="onSubmit(ruleFormRef)"
                >保存</el-button
            >
            <!-- <el-button>Cancel</el-button> -->
        </el-form-item>
    </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue"
import { type FormInstance, type FormRules, ElMessage } from "element-plus"

/** API */
import { ResetPassword } from "@/api/user"

import type { API } from "@/types/user"

// do not use same name with ref
type RuleFrom = API.ResetPassword

const submitLoading = ref<boolean>(false)
const ruleFormRef = ref<FormInstance>()
const form = reactive<RuleFrom>({
    old: "",
    new: "",
    new2: "",
})

const rules = reactive<FormRules<RuleFrom>>({
    old: [{ required: true, message: "密码不能为空" }],
    new: [{ required: true, message: "新密码不能为空" }],
    new2: [
        { required: true, message: "重复密码不能为空" },
        {
            validator: (_, value: string, callback) => {
                if (value !== form.new) {
                    callback(new Error("密码不一样"))
                }

                callback()
            },
        },
    ],
})
const onSubmit = (el: FormInstance | undefined): void => {
    if (!el) return
    el.validate(async (valid) => {
        if (!valid) {
            return
        }
        submitLoading.value = true
        const { code, message } = await ResetPassword(form)
        ElMessage({
            message,
            type: code === 200 ? "success" : "warning",
        })
        submitLoading.value = false
        el.resetFields()
    })
}
</script>
